package com.base.cn.platform.os.controller.qa.record;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.thirdLogin.WXLoginUtils;
import com.base.cn.platform.os.service.course.qa.record.QaTeacherCashRecordService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 后台问答分成记录提现Controller
 *
 * @author s.li
 * @date 2018/11/27
 */
@Controller
public class AdminCashWithdrawalController extends AdminBaseController {
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysTeacherService sysTeacherService;
    @Autowired
    private QaTeacherCashRecordService qaTeacherCashRecordService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 申请结算页面
     * @param request
     * @param model
     * @param recordType 记录类型，1问答分成，2旁听分成
     * @return 操作页面
     */
    @RequestMapping("/admin/qa/record/cashWithdrawal")
    public String cashWithdrawal(HttpServletRequest request,
                                 Model model,@RequestParam("recordType") int recordType){
        JsonObject sysUser = loginUtil.getLoginUser(request);
        BigDecimal teacherId = sysUser.get("teacherId").getAsBigDecimal();
        Map<String,Object> teacherMap = sysTeacherService.findSysTeacherById(teacherId,false,false,false,false,false);
        if(teacherMap==null){
            teacherMap = new HashMap<>();
        }
        model.addAttribute("teacherMap",teacherMap);
        model.addAttribute("recordType",recordType);
        return resultPage("/qa/record/cash-withdrawal");
    }

    /**
     * 支付宝账号提现
     * @param request HttpServletRequest
     * @param teacherId 老师ID
     * @param account 账号
     * @param realName 账号名真实姓名
     * @param recordType 记录类型，1问答分成，2旁听分成
     * @return Map<String,Object>
     */
    @RequestMapping("/admin/qa/cash/zfbCashWithdrawal")
    @ResponseBody
    public Map<String,Object> zfbCashWithdrawal(HttpServletRequest request,
                                                @RequestParam("teacherId") BigDecimal teacherId,
                                                @RequestParam("account") String account,
                                                @RequestParam("realName") String realName,
                                                @RequestParam("recordType") int recordType){
        BigDecimal sysUserId = loginUtil.getLoginUserId(request);
        Map<String,Object> teacher = new HashMap<>();
        teacher.put("id",teacherId);
        teacher.put("account",account);
        teacher.put("accountType",1);
        teacher.put("realName",realName);
        Map<String,Object> resultMap = sysTeacherService.updateTeacherAccount(teacher);
        if(ResultUtil.getSuccess(resultMap)){
            resultMap = qaTeacherCashRecordService.createQaTeacherCashRecord(teacherId,1,account,realName,sysUserId,recordType);
        }
        return resultMap;
    }

    /**
     * 绑定微信
     * @param request
     * @param teacherId
     * @param realName
     * @param recordType
     * @return
     */
    @RequestMapping("/admin/qa/cash/bindingWeiXin")
    @ResponseBody
    public Map<String,Object> bindingWeiXin(HttpServletRequest request,
                                @RequestParam("teacherId") BigDecimal teacherId,
                                @RequestParam("realName") String realName,
                                @RequestParam("recordType") int recordType){
        if(StringUtils.isEmpty(realName)){
            return ResultUtil.ERROR("请填写提现微信账户的真实姓名");
        }
        if(!DataUtil.idIsNotNull(teacherId)){
            return ResultUtil.ERROR("提现讲师数据不存在");
        }
        if(recordType !=1 && recordType !=2){
            return ResultUtil.ERROR("提现数据类型错误");
        }
        String contextPath = request.getRequestURL().toString().split(request.getRequestURI())[0];
        BigDecimal sysUserId = loginUtil.getLoginUserId(request);
        String signVal = sysUserId+"_"+teacherId+"_"+recordType+"_"+realName;
        String key = MD5.getMD5(signVal);
        customCacheChannel.set(J2CacheRegion.THIRTY_DAY_REGION.getKey(), key, signVal);
        String callBack = contextPath + "/qa/cash/getWeiXinCode?sign="+key;
        logger.info("==========================callBack:"+callBack);
        return ResultUtil.SUCCESS("验证成功",callBack);
    }

    /**
     * 获取微信Code
     * @param request
     * @param sign 签名
     * @return 操作页面
     * @throws Exception
     */
    @RequestMapping("/qa/cash/getWeiXinCode")
    public String getWeiXinCode(HttpServletRequest request,
                                @RequestParam("sign") String sign) throws  Exception{
        TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
        String appId = wxConfigMap.get("appId");//如果是微信内置浏览器，则需要公众号的AppId
        String contextPath = request.getRequestURL().toString().split(request.getRequestURI())[0];
        String redirect_uri = contextPath + "/qa/cash/weiXinRedirect";
        //重定向到微信网页授权登录
        StringBuilder callBack = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        callBack.append(appId).append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8"));
        callBack.append("&response_type=code&scope=snsapi_userinfo&state=");
        logger.info("=======================sign:"+sign);
        callBack.append(sign);
        callBack.append("#wechat_redirect");
        return redirect(request,callBack.toString());
    }

    /**
     * 微信获取Code的回调
     * @param request
     * @return 显示结果页面
     * @throws Exception
     */
    @RequestMapping("/qa/cash/weiXinRedirect")
    public String weiXinRedirect(HttpServletRequest request,
                                 RedirectAttributes redirectAttributes) throws Exception{
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String stateVal = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(), state).getValue();
        String message = "系统错误";
        if(StringUtils.isNotEmpty(stateVal)){
            customCacheChannel.exists(J2CacheRegion.THIRTY_DAY_REGION.getKey(),state);
            String[] arr = stateVal.split("_");
            logger.info("===================code:"+code);
            logger.info("===================state:"+state);
            BigDecimal sysUserId = new BigDecimal(arr[0]);
            logger.info("==========================sysUserId:"+sysUserId);
            BigDecimal teacherId = new BigDecimal(arr[1]);
            logger.info("==========================teacherId:"+teacherId);
            int recordType = Integer.parseInt(arr[2]);
            logger.info("==========================recordType:"+recordType);
            String realName = URLDecoder.decode(arr[3],"utf-8");
            logger.info("==========================realName:"+realName);
            TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
            String appId = wxConfigMap.get("appId");//微信公众号appId
            String appSecret= wxConfigMap.get("appSecret");// 微信公众号secret
            //微信的openId和accessToken
            Map<String,String> map = WXLoginUtils.getAccessTokenAndOpendId(appId,appSecret,code);
            String openId = map.get("openId");
            String accessToken = map.get("accessToken");
            logger.info("===================openId:"+openId);
            logger.info("===================accessToken:"+accessToken);
            Map<String,Object> teacher = new HashMap<>();
            teacher.put("id",arr[1]);
            teacher.put("account",openId);
            teacher.put("accountType",2);
            teacher.put("realName",realName);
            Map<String,Object> resultMap = sysTeacherService.updateTeacherAccount(teacher);
            if(ResultUtil.getSuccess(resultMap)){
                resultMap = qaTeacherCashRecordService.createQaTeacherCashRecord(teacherId,2,openId,realName,sysUserId,recordType);
            }
            message = ResultUtil.getMessage(resultMap);
        }
        return toRedirectMessage(redirectAttributes,request,message);
    }

    /**
     * 提现微信号绑定回调提示
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/qa/cash/toMessage")
    public String toMessage(HttpServletRequest request,Model model){
        logger.info("=================提现微信号绑定回调提示=============");
        String message = request.getParameter("message");
        logger.info("=======================message:"+message);
        model.addAttribute("message",message);
        return resultPage("/qa/record/wx-callback-message");
    }

    private String toRedirectMessage(RedirectAttributes redirectAttributes,
                                     HttpServletRequest request,String message){
        redirectAttributes.addAttribute("message",message);
        return redirect(request,"/qa/cash/toMessage");
    }
}
